package com.sqgxy.client;

import sun.misc.BASE64Decoder;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

public class ClientServlet {

    public static void main(String[] args) {
        // 完成
        String message = upLoadFile("http://localhost:8080/file/upload", "C:/upload/1.jpg");
        String message1 = downLoadFile("http://localhost:8080/file/download?id=" + message, "C:/upload/2.jpg");
        System.out.println("文件下载:" + message1);
        String message2 = doGet("http://localhost:8080/file/getDate?id=" + message);
        System.out.println("文件json数据\n" + message2);
    }

    // 下载文件
    public static String downLoadFile(String url, String filename){
        URLConnection con = null;
        try {
            con = new URL(url).openConnection();

            // 创建文件
            File file = new File(filename);
            // 如果根目录不存在
            if (!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            // 下载返回的文件
            InputStream in = new DataInputStream(con.getInputStream());
            DataOutputStream out = new DataOutputStream(new FileOutputStream(filename));
            int bytes = 0;
            byte[] bufferOut = new byte[2048];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            BufferedReader buffer = null;
            StringBuffer resultBuffer = null;
            try {
                //得到响应流
                InputStream inputStream = con.getInputStream();
                //将响应流转换成字符串
                resultBuffer = new StringBuffer();
                String line;
                buffer = new BufferedReader(new InputStreamReader(inputStream));
                while ((line = buffer.readLine()) != null) {
                    resultBuffer.append(line);
                }
                return resultBuffer.toString();
            }catch (Exception e){
                return "";
            }
        }catch (Exception e){
            System.out.println("下载文件异常");
            e.printStackTrace();
        }
        return "下载失败";
    }

    public static int TurnFile(String fileStream ,String path) {
        int flag=0;
        System.out.println(fileStream.getBytes().length);
        try {
            byte[] byteStream = new BASE64Decoder().decodeBuffer(fileStream);
            System.out.println("base64解码:=" + byteStream);
            OutputStream out = new FileOutputStream(path);
            out.write(byteStream, 0, byteStream.length);
            out.flush();
            out.close();
            flag=1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static String upLoadFile(String url, String filePath) {
        DataOutputStream outputStream = null;
        BufferedReader reader = null;
        String result = "";
        try {
            // 连接设置
            URL realUrl = new URL(url);
            // 打开和URL之间的链接
            HttpURLConnection con = (HttpURLConnection) realUrl.openConnection();
            // 发送POST请求必须设置以下两行
            con.setDoOutput(true);
            con.setDoInput(true);

            String BOUNDARY = "----WebKitFormBoundaryGbm6yYc5V2yilQRE";  // 定义数据分隔线
            con.setUseCaches(false);
            con.setRequestMethod("POST");
            con.setRequestProperty("connection", "Keep-Alive");
            con.setRequestProperty("user-agent", "MOzilla/4.0 (compatible; MSIE 6.0;Windows NT 5.1; SV1)");
            con.setRequestProperty("Charsert", "UTF-8");
            con.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + BOUNDARY);
            con.connect();

            outputStream = new DataOutputStream(con.getOutputStream());
            // 定义最后文件分割线
            byte[] end_date = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();
            // 添加文件参数
            File file = new File(filePath);
            StringBuilder builder = new StringBuilder();
            builder.append("--");
            builder.append(BOUNDARY);
            builder.append("\r\n");
            builder.append("Content-Disposition: form-data;name=\"file\";filename=\"" + file.getName() + "\"");
            builder.append("\r\n");
            builder.append("\r\n");
            outputStream.write(builder.toString().getBytes());

            DataInputStream in = new DataInputStream(new FileInputStream(file));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }
            // 多文件时，两文件之间加这个
            // outputStream.write("\r\n".getBytes());
            in.close();

            outputStream.write(end_date);
            // flush的缓冲流
            outputStream.flush();
            // 定义BuffererReader输入流来读取URL的响应
            reader = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("请求文件上传异常");
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }



    /**
     * Http get请求
     * @param httpUrl 连接
     * @return 响应数据
     */
    public static String doGet(String httpUrl){
        //链接
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }
}
